package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.BpmnInfo;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.mapper.ServiceItemMapper;
import com.ruoyi.business.service.IBpmnInfoService;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-07
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id) {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param carPackageAudit 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit) {
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit packageAudit : carPackageAudits) {
            //设置创建人
            packageAudit.setCreator(
                    sysUserService.selectUserById(
                            Long.valueOf(packageAudit.getCreator())
                    ).getUserName());

            //设置审核人
            if (packageAudit.getAuditorId() != null) {
                packageAudit.setAuditorName(sysUserService.selectUserById(packageAudit.getAuditorId()).getUserName());
            }
        }
        return carPackageAudits;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param carPackageAudit 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param carPackageAudit 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit) {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids) {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id) {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    /**
     * 提交审核
     *
     * @param serviceItemId 服务单项id
     * @param bpmnInfoId    流程id
     * @param director      审核人店长
     * @param finance       审核人财务
     * @param info          备注
     */
    @Override
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
        //合理化校验,是否套餐
        ServiceItem serviceItem = serviceItemService.selectServiceItemById(serviceItemId);
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage()) ||
                ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus()) ||
                ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) ||
                ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
        ) {
            throw new ServiceException("非法操作!");
        }
        //封装CarPackageAudit对象
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setInfo(info);
        carPackageAudit.setCreateTime(new Date());
        carPackageAudit.setCreator(ShiroUtils.getUserId().toString());
        carPackageAudit.setBpmninfoId(bpmnInfoId);
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
        carPackageAudit.setServiceItemName(serviceItem.getName());
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());
        carPackageAudit.setServiceItemId(serviceItemId);
        carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
        //查询bpmnInfo,
        BpmnInfo bpmnInfo = bpmnInfoService.selectBpmnInfoById(bpmnInfoId);
        //获取到流程定义的key
        String definitionKey = bpmnInfo.getActProcessKey();
        //获取业务标识
        String businessKey = carPackageAudit.getId().toString();
        //储存流程变量
        HashMap<String, Object> map = new HashMap<>();
        map.put("director", director);
        if (finance != null) {
            map.put("finance", finance);
        }
        //启动流程部署实例对象
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(definitionKey, businessKey, map);
        //流程审核对象关联实例对象
        carPackageAudit.setInstanceId(processInstance.getId());
        //查询当前任务处于哪个任务中
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        //获取流程的运行节点,获取节点处理人
        String assignee = task.getAssignee();
        carPackageAudit.setAuditorId(Long.parseLong(assignee));
        this.updateCarPackageAudit(carPackageAudit);
        //更新服务单项状态
        serviceItemMapper.updateSaleStatus(serviceItemId, ServiceItem.AUDITSTATUS_AUDITING);
    }

    /**
     * 撤销审核状态
     * @param id 审核中的id
     */
    @Override
    public void cancelApply(Long id) {
        //合理性校验
        CarPackageAudit carPackageAudit = this.selectCarPackageAuditById(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new ServiceException("非法操作");
        }
        //更新carPackageAudit对象状态
        CarPackageAudit packageAudit = new CarPackageAudit();
        packageAudit.setStatus(CarPackageAudit.STATUS_CANCEL);
        packageAudit.setId(id);
        carPackageAuditMapper.updateCarPackageAudit(packageAudit);
        //更新serviceItem状态
        serviceItemMapper.updateSaleStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        //进行流程删除
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"流程撤销");
    }

    /**
     *
     * @param id 审核中的id
     * @return 返回一个图像输入流
     */
    @Override
    public InputStream processImg(Long id) {
        InputStream inputStream = null;
        //获取carPackageAudit对象
        CarPackageAudit carPackageAudit = this.selectCarPackageAuditById(id);
        Long bpmninfoId = carPackageAudit.getBpmninfoId();
        //通过carPackageAudit对象获取bpmnInfo对象
        BpmnInfo bpmnInfo = bpmnInfoService.selectBpmnInfoById(bpmninfoId);
        //判断 流程进行中,节点高亮  ,  结束 , 只需要流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        List state = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            //审核中,获取单前节点
            state=runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else {
            //结束
            state = Collections.EMPTY_LIST;
        }
        //创建插件对象
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(bpmn模型,需要高亮的节点ID集合,需要高亮的联线id集合)
        inputStream = generator.generateDiagram(bpmnModel,
                state,
                Collections.EMPTY_LIST,
                "微软雅黑",
                "微软雅黑",
                "微软雅黑");//解决乱码

        return inputStream;
    }


    @Override
    public void audit(Long id, Long auditStatus, String info) {

    }

    @Override
    public List<?> queryForRank(CarPackageAudit carPackageAudit) {
        //审批中的
        carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        List<CarPackageAudit> query = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit packageAudit : query) {
            if (packageAudit.getAuditorId() != null) {
                packageAudit.setAuditorName(sysUserService.selectUserById(packageAudit.getAuditorId()).getUserName());
            }
            packageAudit.setCreator(sysUserService.selectUserById(Long.valueOf(packageAudit.getCreator())).getUserName());
        }
        return query;
    }

    @Override
    public List<?> queryForYet(CarPackageAudit carPackageAudit) {
        //结束审批的
        carPackageAudit.setStatus(null);
        List<CarPackageAudit> query = carPackageAuditMapper.mySelectCarPackageAuditList(carPackageAudit,
                CarPackageAudit.STATUS_REJECT,
                CarPackageAudit.STATUS_PASS,
                CarPackageAudit.STATUS_CANCEL);
        for (CarPackageAudit packageAudit : query) {
            if (packageAudit.getAuditorId() != null) {
                packageAudit.setAuditorName(sysUserService.selectUserById(packageAudit.getAuditorId()).getUserName());
            }
            packageAudit.setCreator(sysUserService.selectUserById(Long.valueOf(packageAudit.getCreator())).getUserName());
        }
        return query;
    }
}
